package com.wf.service.impl;

import cn.hutool.core.collection.SpliteratorUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wf.constant.RedisConstant;
import com.wf.domain.*;
import com.wf.dto.Apart_houses;
import com.wf.dto.ContractDTO;
import com.wf.dto.ContractMap;
import com.wf.dto.Houses_facility_DTO;
import com.wf.mapper.ApartmentInfoMapper;
import com.wf.mapper.ContractInfoMapper;
import com.wf.mapper.HousesInfoMapper;
import com.wf.mapper.UserMapper;
import com.wf.service.ContractInfoService;
import com.wf.utils.AliOssUtil;
import com.wf.utils.RedisUtil;
import com.wf.utils.WordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author mpk16
 * @description 针对表【contract_info】的数据库操作Service实现
 * @createDate 2024-08-03 13:39:49
 */
@Service
@DS("master")
public class ContractInfoServiceImpl extends ServiceImpl<ContractInfoMapper, ContractInfo>
        implements ContractInfoService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    HousesInfoMapper housesInfoMapper;
    @Autowired
    ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    ContractInfoMapper contractInfoMapper;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AliOssUtil aliOssUtil;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Map<String, Object> selectConAllInfo(Integer contract_id) {
        Map<String, Object> map = new HashMap<>();
        ContractInfo contractInfo = contractInfoMapper.selectById(contract_id);
        User user = userMapper.selectById(contractInfo.getUserId());
        HousesInfo housesInfo = housesInfoMapper.selectById(contractInfo.getHouseId());
        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(housesInfo.getApartmentId());
        map.put("contract", contractInfo);
        map.put("user", user);
        map.put("house", housesInfo);
        map.put("apartment", apartmentInfo);
        return map;
    }

    /**
     * 获取合同pdf
     *
     * @param contractId
     * @return
     */
    @Override
    public String getContractPdf(String contractId) {
        if (contractId != null) {
            ContractInfo contractInfo = contractInfoMapper.selectById(contractId);
            return contractInfo.getContractStencil();
        }
        return null;
    }

    @Override
    public void updateAllView() {
        contractInfoMapper.updateView();
    }

    @Override
    public List<ContractInfo> selectContract(Integer status, Integer user_id) {
        return contractInfoMapper.selectContract(status,user_id);
    }

    @Override
    public Set<HashMap<String, Object>> selectInvoiceRequest() {
        return redisUtil.sGet("apartment::invoice::apply");
    }

    @Override
    @DS("master")
    public boolean newContract(Apart_houses apartHouses, String phone, Integer money) {
        ContractMap map = generateContractMap(apartHouses, phone, money);
        String upload = upload(map);
        return true;
    }
    @Override
//    @DS("apartment_sys")
    public ContractMap generateContractMap(Apart_houses apartHouses, String phone, Integer money){
        List<HousesInfo> housesInfoList = apartHouses.getHousesInfoList();
        HousesInfo housesInfo = housesInfoList.get(0);
        Houses_facility_DTO housesFacilityDto = housesInfoMapper.selectAllFacilityByHousesId(housesInfo.getHousesId());
        ContractDTO contractDTO = new ContractDTO();
        List<FacilityInfo> facilityInfoList = housesFacilityDto.getFacilityInfoList();
//        System.out.println("facilityInfoList = " + facilityInfoList);
        StringBuilder s = new StringBuilder();
        StringBuilder s1 = new StringBuilder();
        facilityInfoList.stream().filter(facilityInfo -> facilityInfo.getFacilityType()==1).forEach(facilityInfo -> s.append("，"+facilityInfo.getFacilityName()));
        facilityInfoList.stream().filter(facilityInfo -> facilityInfo.getFacilityType()==2).forEach(facilityInfo -> s1.append("，"+facilityInfo.getFacilityName()));
//        System.out.println("s = " + s);
//        System.out.println("s1 = " + s1);
        contractDTO.setLandlordName("悠享公寓租赁平台");
//        System.out.println("String.valueOf(s).substring(1) = " + String.valueOf(s).substring(1));
        contractDTO.setLandlordAddress(apartHouses.getAddress());
        contractDTO.setLandlordPhone(phone);
        contractDTO.setHouseLocation(
                apartHouses.getAddress()
                        +apartHouses.getName()
                        +apartHouses.getUnits()+"单元"
                        +housesInfo.getFloor()
                        +"层"+housesInfo.getNumber());
        contractDTO.setHouseArea(housesInfo.getUsageArea()+"");
        contractDTO.setHouseStructure(housesInfo.getNature());
        contractDTO.setPublicFacilities(String.valueOf(s).substring(1));
        contractDTO.setEnergyFacilities(String.valueOf(s1).substring(1));
        contractDTO.setMonthlyRent(money+"");
        ContractMap contractMap = new ContractMap(contractDTO);
        System.out.println("contractMap = " + contractMap);
        return contractMap;
    }
    @Override
    @DS("master")
    public String upload(ContractMap map) {
        boolean flag = false;
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        long l = snowflake.nextId();
        String pdf;
        try {
            String pre = LocalDateTimeUtil.formatNormal(LocalDate.now());
            WordUtils.compile("template/contractTemplate.docx","D:\\contract\\"+pre+"\\"+l+".docx",map);
            WordUtils.convertToPDF("D:\\contract\\"+pre+"\\"+l+".docx","D:\\contract\\"+pre+"\\"+l+".pdf");
            String docx = aliOssUtil.upload(FileUtil.readBytes("D:\\contract\\" +pre+"\\"+ l + ".docx"), pre+"/template/"+l + ".docx");
            pdf = aliOssUtil.upload(FileUtil.readBytes("D:\\contract\\" +pre+"\\" + l + ".pdf"), pre+"/template/"+l + ".pdf");
            flag = true;
            System.out.println("docx = " + docx);
            System.out.println("pdf = " + pdf);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return pdf;
    }
    @Override
    @DS("master")
    public boolean addContractInfo(Map<String, Object> variables){
        QueryWrapper<HousesInfo> housesInfoQueryWrapper = new QueryWrapper<>();
        String houseLocation = (String) variables.get("houseLocation");
        int i = houseLocation.lastIndexOf("-");
        String s = houseLocation.substring(i - 5);
        housesInfoQueryWrapper.eq("number",s);
        HousesInfo housesInfo = housesInfoMapper.selectOne(housesInfoQueryWrapper);
        ContractInfo contractInfo = new ContractInfo();
        contractInfo.setContractNumber((String) variables.get("contractNumber"));
        contractInfo.setContractStencil((String) variables.get("pdf"));
        contractInfo.setContractType("按月支付");
        contractInfo.setIsDelete(0);
        contractInfo.setPrice(Double.parseDouble(variables.get("monthlyRent")+""));
        contractInfo.setHouseId(housesInfo.getHousesId());
        contractInfo.setStatus(0);
        int insert = contractInfoMapper.insert(contractInfo);
        RedisUtil<String> redisUtil = new RedisUtil<>(stringRedisTemplate);
        redisUtil.set(RedisConstant.APARTMENT_USED_FILE,((String) variables.get("pdf")).replace("https://wfyn.oss-cn-hangzhou.aliyuncs.com/",""));
        boolean flag = false;
        if (insert>0){
            flag=true;
        }
        return flag;
    }
}




